//
//  HZBottomTabBar.m
//  WangYiNews
//
//  Created by WangPengHua on 16/1/10.
//  Copyright © 2016年 PengHua Wang. All rights reserved.
//

#import "HZBottomTabBar.h"
#import "HZBottomTabBarButton.h"
@interface HZBottomTabBar()
@property (nonatomic, strong) UIButton *selectedButton;
@end
@implementation HZBottomTabBar
- (void)addBottomBarButtonWithNormalImageName:(NSString *)normal selected:(NSString *)selected title:(NSString *)title{
    //1.创建按钮
    HZBottomTabBarButton *button = [[HZBottomTabBarButton alloc]init];
    //2.设置按钮的背景图片
    [button setImage:[UIImage imageNamed:normal] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:selected] forState:UIControlStateSelected];
    
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
    //3.将按钮添加到底部的bottomTabBar中
    [self addSubview:button];
    
    //4.给按钮添加绑定事件
    [button addTarget:self action:@selector(didClickTabBarButton:) forControlEvents:UIControlEventTouchDown];
    
}
#pragma mark - 布局子控件
- (void)layoutSubviews{
    [super layoutSubviews];
    //获取按钮的在长度
    NSUInteger count = self.subviews.count;
    //设置frame
    CGFloat w = self.width / count;
    CGFloat h = self.height;
    CGFloat y = 0;
    for (int i = 0; i < count; i++) {
        CGFloat x = i * w ;
        //获取对应的按钮,设置frame
        UIButton *button = self.subviews[i];
        button.frame = CGRectMake(x, y, w, h);
        //为每个按钮绑定tag值
        button.tag = i;
        //如果是第0个按钮,设置按钮为选中状态
        if (i == 0) {
            button.selected = YES;
            self.selectedButton = button;
        }
    }
}

- (void)didClickTabBarButton:(UIButton *)button{
    NSLog(@"按钮被点击了");
    //1.让当前按钮的选择状态取消选中
    self.selectedButton.selected = NO;
    //2.设置传进来的按钮的选中状态(也就是被点击的按钮)
    button.selected = YES;
    //3.记录当前被点击的按钮为当前选中按钮
    self.selectedButton = button;
    NSLog(@"tag = %ld",(long)button.tag);
    int index = (int)button.tag;
    //4. 判断代理是否实现了代理方法,如果实现了,就调用
    if ([self.delegate respondsToSelector:@selector(bottomTabBar:didCurrentClickButtonIndex:)]) {
        [self.delegate bottomTabBar:self didCurrentClickButtonIndex:index];
    }
}
@end
